#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Software : PyCharm
# @Time    : 2024-12-18 11:06
# @Author  : gzh
# @File : TkParent.py

"""
最初主要是为了实现字体的自适应大小功能后来添加了其他属性
"""

import os
import subprocess
import sys
import time
import traceback
from tkinter import Tk, StringVar
from tkinter import font as tkf

class TkParent(Tk):
    def __init__(self):
        super().__init__()
        self.__default_w = 800  # 默认界面宽度
        self.__default_h = 480  # 默认界面高度
        self._font_dict: dict = {}  # 储存所有字体类型
        self._font_dict_set: dict = {}  # 储存所有字体设置
        self.__ki = 1  # 缩放比例
        self.now_w = 1  # 页面实际宽度
        self.now_h = 1  # 页面实际高度
        self.Ymd = StringVar(master=self)  # 年月日
        self.HMS = StringVar(master=self)  # 时分秒
        self.f30 = self.new_font(30)
        self.f25 = self.new_font(25)
        self.f22 = self.new_font(22)
        self.f20 = self.new_font(20)
        self.f18 = self.new_font(18)
        self.f15 = self.new_font(15)
        self.f13 = self.new_font(13)
        self.bind("<Configure>", lambda event: self.__font_size_set())  # 绑定字体设置
        self.timeUpdate()

    def window_default(self, title, geometry):  # 程序默认通用设置
        self.title(title)
        self.protocol("WM_DELETE_WINDOW", self.quit_app)
        # normal, iconic, withdrawn, or zoomed
        # flat, groove, raised, ridge, solid, or sunken  # 边框样式
        # self.state('zoomed')
        # self.wm_overrideredirect(True)
        self.geometry('{}x{}+{}+{}'.format(*geometry))
        self.option_add("*TCombobox*font", self.f15)  # 设置Combobox字体
        self.option_add("*Button*Relief", 'raised')  # 设置Button边框样式
        self.option_add("*Button*BorderWidth", 2)  # 设置Button边框宽度
        self.option_add("*Button*font", self.f15)  # 设置Button字体

        self.option_add("*Label*justify", 'center')
        self.option_add("*Entry*justify", 'center')


    def __font_size_set(self) -> None:
        """
        字体大小更新
        """
        tkw2 = self.winfo_width()
        tkh2 = self.winfo_height()
        if self.now_w != tkw2 or self.now_h != tkh2:
            self.now_w = tkw2
            self.now_h = tkh2
            xk = tkw2 / self.__default_w
            yk = tkh2 / self.__default_h
            self.__ki = xk if xk < yk else yk
            for i in self._font_dict.keys():
                size = self._font_dict_set[i][0]
                fontsize1 = int(size * self.__ki) + 1
                self._font_dict[i].configure(size=fontsize1,
                                             family=self._font_dict_set[i][1],
                                             weight=self._font_dict_set[i][2])

    def _new_font(self, size, weight, family):
        """
        创建新的字体
        """
        if weight == 'normal':
            name = f'f{size}'
            if name not in self._font_dict.keys():
                self._font_dict[name] = tkf.Font(size=size, family=family, weight=weight)
                self._font_dict_set[name] = [size, family, weight]
        else:
            name = f'f{size}b'
            if name not in self._font_dict.keys():
                self._font_dict[name] = tkf.Font(size=size, family=family, weight=weight)
                self._font_dict_set[name] = [size, family, weight]
        return self._font_dict[name]

    def new_font(self, size: int, weight: str = 'normal', family: str = '楷体'):
        font = self._new_font(size, weight, family)
        return font

    def timeUpdate(self):  # 时间更新函数
        self.Ymd.set(time.strftime('%Y-%m-%d'))
        self.HMS.set(time.strftime('%H:%M:%S'))
        self.after(1000, self.timeUpdate)

    def start(self):  # 程序启动
        self.mainloop()

    def close_pc(self):  # 关闭程序并关机
        self.quit()
        os.system('shutdown /s /t 0 -hybrid')
        subprocess.run(["sudo", "shutdown", "-h", "now"], check=True)
        sys.exit(0)

    def quit_app(self):  # 退出程序
        self.quit()

    @property
    def winfo_ki(self):  # 返回缩放比例
        return  self.__ki

    def report_callback_exception(self, exc, val, tb):  # 重写日志输出，将日志保存起来
        print("Exception in Tkinter callback", file=sys.stderr)
        sys.last_type = exc
        sys.last_value = val
        sys.last_traceback = tb
        traceback.print_exception(exc, val, tb)
        path = os.path.join(os.getcwd(), 'cache')
        if not os.path.exists(path):
            os.makedirs(path)

        with open(os.path.join(path, 'loggo.log'), 'a', encoding="utf-8") as file:
            file.write(f"[{time.strftime('%Y%m%d%H%M%S')}] Unhandled exception occurred:\n")
            traceback.print_exception(exc, val, tb, file=file)
